<template>
  <div class="app-container">
    <TheQueryForm :option="searchOption" @onSubmit="onSubmit" @onClear="onClear"></TheQueryForm>
    <el-row style="margin-bottom: 20px">
      <el-col :span="12">
        <el-radio-group size="small" v-model="queryParams.saleStatus">
          <el-radio-button label>全部</el-radio-button>
          <el-radio-button label="WAITING" style="position: relative">
            待处理
            <el-badge
              v-if="salesAfterCount.waitCount"
              class="badge"
              :value="salesAfterCount.waitCount"
              :max="99"
            ></el-badge>
          </el-radio-button>
          <el-radio-button label="FINISH">已完成</el-radio-button>
          <el-radio-button label="CANCEL">已取消</el-radio-button>
          <el-radio-button label="REFUSE">已拒绝</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" style="display: flex; justify-content: flex-end">
        <el-button size="small" type="primary" @click="handleCreate">创建售后单</el-button>
        <el-button size="small" :loading="exportLoading" @click="handleExport">导出Excel</el-button>
      </el-col>
    </el-row>
    <TheTable
      ref="tableRefs"
      :tableOption="tableOption"
      :pageNo.sync="pageNo"
      :limit.sync="limit"
      :api="queryPageApi"
      :queryParams="queryParams"
      :autoPlay="false"
      :renderFunc="renderFunc"
    />
    <Apply ref="applyRefs" @refresh="onRefresh" />
    <ResultDialog ref="resultRefs" @done="onRefresh" />
    <resultSaasDialog ref="resultSaasRefs" @done="onRefresh" />
  </div>
</template>
<script>
import ResultDialog from "./components/resultDialog.vue";
import resultSaasDialog from "./components/resultSaasDialog.vue";

import Apply from "./components/apply.vue";
import { apiMerchantPage } from "@/api/storeManager.js";
import {
  apiServiceSaleReturnBPage,
  apiServiceSaleReturnBStatusCount,
  apiServiceSaleReturnBExport,
  apiOrderBApplyRefund,
  apiServiceSaleReturnBRefuse
} from "@/api/salesAfter.js";
export default {
  components: { Apply, ResultDialog, resultSaasDialog },
  data() {
    const _this = this;
    return {
      salesAfterCount: {
        waitCount: 0,
        cancelCount: 0,
        refuseCount: 0,
        finishCount: 0
      },
      queryPageApi: apiServiceSaleReturnBPage,
      queryParams: { saleStatus: "" },
      pageNo: 1,
      limit: 10,
      exportLoading: false,
      searchOption: [
        {
          field: "serviceSaleReturnId",
          label: "售后单id",
          placeholder: "售后单id",
          type: "Input"
        },
        {
          field: "serviceOrderId",
          label: "订单id",
          placeholder: "订单id",
          type: "Input"
        },

        {
          type: "Select",
          field: "merchantName",
          label: "商家名称",
          placeholder: "商家名称",
          options: [],
          api: apiMerchantPage,
          params: { pageNum: 1, pageSize: -1 },
          optionsKey: "merchantContactName",
          optionsValue: "merchantContactName"
        },
        {
          type: "Input",
          field: "workerMobile",
          label: "师傅手机号",
          placeholder: "师傅手机号"
        },
        {
          type: "DatePickerRange",
          field: "time",
          label: "创建时间",
          placeholder: "创建时间"
        }
      ],
      tableOption: [
        {
          label: "售后单id",
          prop: "serviceSaleReturnId",
          width: 150
        },
        {
          label: "关联订单id",
          prop: "serviceOrderId",
          width: 150,
          render(h, { row }) {
            const url = `/order/platformDetail?serviceOrderId=${row.serviceOrderId}`;
            return (
              <router-link to={url}>
                <el-link underline={false} type="primary">
                  {row.serviceOrderId}
                </el-link>
              </router-link>
            );
          }
        },
        {
          label: "商家",
          prop: "merchantName",
          width: 180,
          formatter({ merchantName }) {
            return `名称:${merchantName}`;
          }
        },
        {
          label: "师傅",
          width: 120,
          prop: "workerInfo",
          render(createElement, { row }) {
            try {
              const dom = (
                <div>
                  <div>师傅id：{row.workerId}</div>
                  <div>姓名：{row.workerName}</div>
                  <div>手机号：{row.workerMobile}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "状态",
          width: 80,
          prop: "saleStatus",
          formatter({ saleStatus }) {
            return this.$filters.filterSaleStatusEnum(saleStatus);
          }
        },
        {
          label: "创建时间",
          width: 100,
          prop: "createTime",
          render(createElement, { row }) {
            try {
              const strArr = row.createTime.split(" ");
              const dom = (
                <div>
                  <div>{strArr[0]}</div>
                  <div>{strArr[1]}</div>
                </div>
              );
              return dom;
            } catch (error) {
              return <div></div>;
            }
          }
        },
        {
          label: "操作",
          width: 120,
          prop: "operate",
          fixed: "right",
          render(h, { row }) {
            return h("div", [
              h("el-link", {
                domProps: {
                  innerHTML: "去处理"
                },
                props: {
                  type: "warning"
                },
                directives: [
                  {
                    name: "column-domItem-show",
                    value: ["WAITING"].includes(row.saleStatus) //待处理阶段显示
                  }
                ],
                on: {
                  click() {
                    if (row.liugeFlag) {
                      _this.$refs.resultRefs.open({
                        serviceSaleReturnId: row.serviceSaleReturnId,
                        liugeFlag: row.liugeFlag
                      });
                    } else {
                      _this.$refs.resultSaasRefs.open({
                        serviceSaleReturnId: row.serviceSaleReturnId
                      });
                    }
                  }
                }
              }),
              h("el-link", {
                domProps: {
                  innerHTML: "拒绝售后"
                },
                props: {
                  type: "danger"
                },
                directives: [
                  {
                    name: "column-domItem-show",
                    value: ["WAITING"].includes(row.saleStatus) //待处理阶段显示
                  }
                ],
                on: {
                  click() {
                    _this.onPlatformRefuse(row.serviceSaleReturnId);
                  }
                }
              }),
              h("el-link", {
                domProps: {
                  innerHTML: "查看详情"
                },
                directives: [
                  {
                    name: "column-domItem-show",
                    value: !["WAITING"].includes(row.saleStatus) //非待处理阶段显示
                  }
                ],
                props: {
                  type: "primary"
                },
                on: {
                  click() {
                    _this.$router.push({
                      path: "/salesAfter/detail",

                      query: {
                        serviceSaleReturnId: row.serviceSaleReturnId,
                        liugeFlag: row.liugeFlag
                      }
                    });
                  }
                }
              })
            ]);
          }
        }
      ]
    };
  },
  mounted() {},
  methods: {
    // 平台独有拒绝售后
    onPlatformRefuse(serviceSaleReturnId) {
      this.$prompt("此操作将拒绝售后订单, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: value => {
          if (!value) {
            return "请输入拒绝原因!";
          } else if (value.length > 40) {
            return "最多支持40个字符!";
          } else {
            return true;
          }
        }
      })
        .then(({ value }) => {
          apiServiceSaleReturnBRefuse({
            serviceSaleReturnId: serviceSaleReturnId,
            refuseReason: value
          }).then(res => {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.$refs.tableRefs.refresh();
          });
        })
        .catch(() => {});
    },
    renderFunc(res) {
      apiServiceSaleReturnBStatusCount({}).then(res => {
        this.salesAfterCount = {
          waitCount: res.data.waitCount, //待处理订单数
          cancelCount: res.data.cancelCount, //已取消订单数
          refuseCount: res.data.refuseCount, //已拒绝订单数
          finishCount: res.data.finishCount //已完成订单数
        };
      });
      return res;
    },
    handleCreate(row) {
      this.$refs.applyRefs.open();
    },
    // 导出
    async handleExport() {
      this.exportLoading = true;
      const res = await apiServiceSaleReturnBExport({
        ...this.queryParams
      });
      if (res.code === "SUCCESS") {
        let header = [
          {
            title: "售后单id",
            prop: "serviceSaleReturnId",
            valueType: "s"
          },
          {
            title: "关联订单id",
            prop: "serviceOrderId",
            valueType: "s"
          },
          {
            title: "商家",
            prop: "merchantName",
            valueType: "s"
          },
          {
            title: "师傅",
            prop: "",
            children: [
              {
                title: "师傅id",
                prop: "workerId",
                valueType: "s"
              },

              {
                title: "姓名",
                prop: "workerName",
                valueType: "s"
              },

              {
                title: "手机号",
                prop: "workerMobile",
                valueType: "s"
              }
            ]
          },
          {
            title: "状态",
            prop: "saleStatus",
            valueType: "s"
          },
          {
            title: "创建时间",
            prop: "createTime",
            valueType: "s"
          }
        ];

        let dataSource = res.data.map(item => {
          return {
            ...item,
            saleStatus: this.$filters.filterSaleStatusEnum(item.saleStatus)
          };
        });
        const option = {
          dataSource: dataSource,
          header: header,
          fileName: "售后订单"
        };
        window.$Json2Excel(option);
        this.exportLoading = false;
      } else {
        this.$message({
          message: "导出操作失败,请重试",
          type: "warring"
        });
        this.exportLoading = false;
      }
    },
    onRefresh() {
      this.$refs.tableRefs.refresh();
    },
    onSubmit({ values }) {
      console.log(values);
      if (values.hasOwnProperty("time")) {
        values = {
          ...values,
          createTimeStart: values.time ? values.time[0] : "",
          createTimeEnd: values.time ? values.time[1] : ""
        };
        delete values.time;
      }
      this.queryParams = { ...this.queryParams, ...values };
    },
    onClear() {
      this.queryParams = {};
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-link {
  margin: 0 5px;
}
.badge {
  position: absolute;
  right: -0px;
  top: -10px;
  transform: scale(0.9);
}
</style>
